package com.agent.platform.controller;

import com.agent.platform.dto.CreateAgentRequest;
import com.agent.platform.entity.Agent;
import com.agent.platform.service.AgentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理API控制器 - 端口3001 (通过Actuator管理端口)
 * 对应Node.js版本的管理API
 */
@Tag(name = "管理API", description = "Agent CRUD和系统管理接口 (端口3001)")
@Slf4j
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminApiController {

    private final AgentService agentService;

    /**
     * 创建Agent
     * POST /admin/agents
     */
    @Operation(
        summary = "创建Agent",
        description = "创建一个新的Agent实例，配置独立的上下文管理器、工具管理器和控制参数",
        responses = {
            @ApiResponse(responseCode = "201", description = "Agent创建成功"),
            @ApiResponse(responseCode = "400", description = "请求参数无效"),
            @ApiResponse(responseCode = "409", description = "Agent ID已存在")
        }
    )
    @PostMapping("/agents")
    public ResponseEntity<Agent> createAgent(
        @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "Agent创建请求",
            content = @Content(schema = @Schema(implementation = CreateAgentRequest.class))
        )
        @Valid @RequestBody CreateAgentRequest request
    ) {
        log.info("Creating agent: {}", request.getAgentId());
        Agent agent = agentService.createAgent(request);
        return ResponseEntity.status(HttpStatus.CREATED).body(agent);
    }

    /**
     * 获取Agent信息
     * GET /admin/agents/:agentId
     */
    @Operation(
        summary = "获取Agent信息",
        description = "获取指定Agent的完整配置信息",
        responses = {
            @ApiResponse(responseCode = "200", description = "成功获取Agent信息"),
            @ApiResponse(responseCode = "404", description = "Agent不存在")
        }
    )
    @GetMapping("/agents/{agentId}")
    public ResponseEntity<Agent> getAgent(
        @Parameter(description = "Agent ID", required = true) @PathVariable String agentId
    ) {
        Agent agent = agentService.getAgent(agentId);
        return ResponseEntity.ok(agent);
    }

    /**
     * 更新Agent配置
     * PUT /admin/agents/:agentId
     */
    @Operation(
        summary = "更新Agent配置",
        description = "更新Agent的完整配置，包括URL、控制参数和元数据",
        responses = {
            @ApiResponse(responseCode = "200", description = "Agent更新成功"),
            @ApiResponse(responseCode = "404", description = "Agent不存在"),
            @ApiResponse(responseCode = "400", description = "请求参数无效")
        }
    )
    @PutMapping("/agents/{agentId}")
    public ResponseEntity<Agent> updateAgent(
        @Parameter(description = "Agent ID", required = true) @PathVariable String agentId,
        @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "Agent更新请求",
            content = @Content(schema = @Schema(implementation = CreateAgentRequest.class))
        )
        @Valid @RequestBody CreateAgentRequest request
    ) {
        log.info("Updating agent: {}", agentId);
        Agent agent = agentService.updateAgent(agentId, request);
        return ResponseEntity.ok(agent);
    }

    /**
     * 删除Agent
     * DELETE /admin/agents/:agentId
     */
    @Operation(
        summary = "删除Agent",
        description = "删除指定的Agent，可选择强制删除（即使有活动会话）",
        responses = {
            @ApiResponse(responseCode = "200", description = "Agent删除成功"),
            @ApiResponse(responseCode = "404", description = "Agent不存在"),
            @ApiResponse(responseCode = "400", description = "Agent有活动会话且未使用force参数")
        }
    )
    @DeleteMapping("/agents/{agentId}")
    public ResponseEntity<Map<String, Object>> deleteAgent(
        @Parameter(description = "Agent ID", required = true) @PathVariable String agentId,
        @Parameter(description = "是否强制删除", required = false)
        @RequestParam(required = false, defaultValue = "false") boolean force
    ) {
        log.info("Deleting agent: {} force: {}", agentId, force);
        agentService.deleteAgent(agentId, force);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("agentId", agentId);
        response.put("deleted", true);

        return ResponseEntity.ok(response);
    }

    /**
     * 列出所有Agent
     * GET /admin/agents
     */
    @Operation(
        summary = "列出所有Agent",
        description = "获取Agent列表，支持按状态过滤和分页",
        responses = {
            @ApiResponse(responseCode = "200", description = "成功获取Agent列表")
        }
    )
    @GetMapping("/agents")
    public ResponseEntity<Map<String, Object>> listAgents(
        @Parameter(description = "状态过滤 (active/inactive/deleted)", required = false)
        @RequestParam(required = false) String status,
        @Parameter(description = "分页限制", required = false)
        @RequestParam(required = false, defaultValue = "50") int limit,
        @Parameter(description = "分页偏移", required = false)
        @RequestParam(required = false, defaultValue = "0") int offset
    ) {
        List<Agent> agents = agentService.listAgents(status);

        // 简单分页
        int total = agents.size();
        int start = Math.min(offset, total);
        int end = Math.min(offset + limit, total);
        List<Agent> paged = agents.subList(start, end);

        Map<String, Object> response = new HashMap<>();
        response.put("agents", paged);
        response.put("total", total);
        response.put("limit", limit);
        response.put("offset", offset);

        return ResponseEntity.ok(response);
    }

    /**
     * 验证Agent配置
     * POST /admin/agents/:agentId/validate
     */
    @Operation(
        summary = "验证Agent配置",
        description = "验证Agent的配置是否有效",
        responses = {
            @ApiResponse(responseCode = "200", description = "验证完成"),
            @ApiResponse(responseCode = "404", description = "Agent不存在")
        }
    )
    @PostMapping("/agents/{agentId}/validate")
    public ResponseEntity<Map<String, Object>> validateAgent(
        @Parameter(description = "Agent ID", required = true) @PathVariable String agentId
    ) {
        Agent agent = agentService.getAgent(agentId);

        Map<String, Object> validation = new HashMap<>();
        validation.put("valid", true);
        validation.put("agentId", agent.getAgentId());
        validation.put("status", agent.getStatus());

        Map<String, Object> response = new HashMap<>();
        response.put("validation", validation);

        return ResponseEntity.ok(response);
    }

    /**
     * 系统统计
     * GET /admin/system/stats
     */
    @Operation(
        summary = "系统统计信息",
        description = "获取系统级别的统计信息，包括Agent总数、活跃Agent数等",
        responses = {
            @ApiResponse(responseCode = "200", description = "成功获取统计信息")
        }
    )
    @GetMapping("/system/stats")
    public ResponseEntity<Map<String, Object>> systemStats() {
        List<Agent> allAgents = agentService.listAgents(null);
        long activeAgents = allAgents.stream()
            .filter(a -> "active".equals(a.getStatus()))
            .count();

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalAgents", allAgents.size());
        stats.put("activeAgents", activeAgents);
        stats.put("timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(stats);
    }

    /**
     * 健康检查
     * GET /admin/health
     */
    @Operation(
        summary = "管理API健康检查",
        description = "检查管理API服务是否正常运行",
        responses = {
            @ApiResponse(responseCode = "200", description = "服务正常")
        }
    )
    @GetMapping("/health")
    public ResponseEntity<Map<String, String>> health() {
        Map<String, String> response = new HashMap<>();
        response.put("status", "ok");
        response.put("service", "agent-platform-admin-api");
        return ResponseEntity.ok(response);
    }
}
